{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Jpg转PNG时使白色部分透明的方法比较"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext memory_profiler\n",
    "\n",
    "import os, sys\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "\n",
    "fname = os.path.join(os.path.abspath(\"\"), 'image.jpg')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 直接遍历像素，直接在原数组上替换\n",
    "\n",
    "这种方法比较慢，但能处理比较大的图片而不会内存耗尽"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "281 ms ± 10.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n",
      "peak memory: 108.79 MiB, increment: 11.25 MiB\n"
     ]
    }
   ],
   "source": [
    "img = Image.open(fname)\n",
    "\n",
    "def convert1():\n",
    "    '''\n",
    "    直接替换\n",
    "    '''\n",
    "    imga = img.convert('RGBA')\n",
    "    pixdata = imga.load()\n",
    "    width, height = imga.size\n",
    "    for y in range(height):\n",
    "        for x in range(width):\n",
    "            if pixdata[x, y] == (255, 255, 255, 255):\n",
    "                pixdata[x, y] = (255, 255, 255, 0)\n",
    "    return imga\n",
    "\n",
    "%timeit convert1()\n",
    "%memit convert1()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用numpy操作矩阵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "29.8 ms ± 1.09 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n",
      "peak memory: 108.93 MiB, increment: 0.00 MiB\n"
     ]
    }
   ],
   "source": [
    "img = Image.open(fname)\n",
    "\n",
    "def convert3():\n",
    "    imga = img.convert(\"RGBA\")\n",
    "\n",
    "    imga = np.asarray(imga)\n",
    "    r, g, b, a = np.rollaxis(imga, axis = -1)\n",
    "    r_m = r != 255\n",
    "    g_m = g != 255\n",
    "    b_m = b != 255\n",
    "\n",
    "    a = a * ((r_m == 1) | (g_m == 1) | (b_m == 1))\n",
    "    imga = Image.fromarray(np.dstack([r, g, b, a]), 'RGBA')\n",
    "    return imga\n",
    "\n",
    "%timeit convert3()\n",
    "%memit convert3()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
